package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.service.ApCollectionService;
import com.heima.common.cache.CacheService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.model.article.dtos.CollectionBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.schedule.dto.Task;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ApReadBehaviorServiceImpl implements ApCollectionService {

    @Autowired
    private CacheService cacheService;

    @Override
    public ResponseResult collection(CollectionBehaviorDto dto) {
            if (dto == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
            }
            ApUser user = AppThreadLocalUtil.getUser();
            if (user == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }
        Integer id = user.getId();
        Long entryId = dto.getEntryId();
        Short type = dto.getType();
        if (type==0){
        Object O= cacheService.hGet(BehaviorConstants.COLLECTION_BEHAVIOR+entryId.toString(),id.toString());

        if (O!=null){
            ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "已收藏");
        }

            cacheService.hPut(BehaviorConstants.COLLECTION_BEHAVIOR + entryId, id.toString(), JSON.toJSONString(dto));
        }else if (1== type){
            cacheService.hDelete(BehaviorConstants.COLLECTION_BEHAVIOR + entryId, id.toString());
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
